﻿using MicroMVVM.Interfaces;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;

namespace MicroMVVM.Services.Any
{
    [ExportService(ServiceType.Any, typeof (IVisualStateManager), PartCreationPolicy.Transient)]
    public class VisualStateManagerService : VisualStateManager, IVisualStateManager
    {
        private readonly IViewAware _viewAware;

        /// <summary>
        /// Gets the current visual state.
        /// </summary>
        public string State { get; private set; }

        public VisualStateManagerService(IViewAware viewAware)
        {
            _viewAware = viewAware;
        }

        /// <summary>
        /// Changes the visual state of the page to the one specified as parameter.
        /// </summary>
        /// <param name="stateName">Visual State name</param>
        /// <returns>True/False</returns>
        public bool GoToVisualState(string stateName)
        {
            State = stateName;

            var control = _viewAware.Current;

            if (control != null) return GoToState(control, stateName, true);

            _viewAware.RaiseControl = ctrl =>
                                          {
                                              if ((ctrl != null) && (ctrl.Dispatcher != null))
                                                  ctrl.Dispatcher.RunAsync(CoreDispatcherPriority.Normal,
                                                                           () => GoToState(ctrl, stateName, true));
                                          };

            return false;
        }

        /// <summary>
        /// Changes visual state of the specified control.
        /// </summary>
        /// <param name="control">Control</param>
        /// <param name="stateName">Visual State name</param>
        /// <param name="useTransitions">Uses transitions</param>
        /// <returns>True/False</returns>
        public bool GoToVisualState(Control control, string stateName, bool useTransitions)
        {
            State = stateName;

            return control != null && GoToState(control, stateName, useTransitions);
        }
    }
}